//
//  PeopleDetailViewController.m
//  cityStar
//
//  Created by apple on 14/12/14.
//  Copyright (c) 2014年 tiny. All rights reserved.
//

#import "PeopleDetailViewController.h"
#import "HTDefine.h"
#import "UIActionSheet+Blocks.h"
#import "SVProgressHUD.h"
#import "PersonalDetail.h"
#import "UIImageView+WebCache.h"
#import "HttpRequestManager.h"
#import "KInterFace.h"
#import "UpLoadImageManager.h"

@interface PeopleDetailViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imgHead;
@property (weak, nonatomic) IBOutlet UILabel *lblName;
@property (weak, nonatomic) IBOutlet UILabel *lblLevel;
@property (weak, nonatomic) IBOutlet UILabel *lblStorage;
@property (weak, nonatomic) IBOutlet UIView *vShow;
@property (weak, nonatomic) IBOutlet UITextField *txfName;
@property (weak, nonatomic) IBOutlet UIButton *btnSure;
@property (weak, nonatomic) IBOutlet UIButton *btnCancel;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;

@end

@implementation PeopleDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self initNavBar];
    [self initViews];
    self.backBtn.layer.cornerRadius = 4;
    self.view.backgroundColor = kBackgroundColor;
    [self addGestures];
    self.txfName.returnKeyType = UIReturnKeyDone;
    self.txfName.delegate = self;
    
    NSData *userData = [KStandUserDefaults objectForKey:KUserDefaultKey_PersonalDetail];
    PersonalDetail *user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    [self.imgHead sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.icszx.com/image/c/id/%@/w/160/h/155/m/0",user.avatar]] placeholderImage:[UIImage imageNamed:@"头像@"]];
    self.lblName.text = [NSString stringWithFormat:@"%@",user.nickname];
    self.lblLevel.text = [NSString stringWithFormat:@"%@",[user.level intValue] == 1?@"普通会员":@"白金会员"];
    self.lblStorage.text = [NSString stringWithFormat:@"用户积分：%@",user.score];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    
}

#pragma mark - UIKeyBoard Notification Methods
- (void)keyboardWillShow:(NSNotification *)notification
{
    [self changeViewFrameWithKeyBoardNotification:notification isShow:YES];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
    [self changeViewFrameWithKeyBoardNotification:notification isShow:NO];
}

- (void)changeViewFrameWithKeyBoardNotification:(NSNotification *)notification isShow:(BOOL)isShow
{
    NSDictionary *userInfo = [notification userInfo];
    NSNumber *animationDur = userInfo[UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *animationCur = userInfo[UIKeyboardAnimationCurveUserInfoKey];
    [UIView beginAnimations:@"changeViewFrame" context:nil];
    [UIView setAnimationCurve:[animationCur integerValue]];
    [UIView setAnimationDuration:[animationDur doubleValue]];
    [self.view setFrame:CGRectMake(0, isShow?-80:64, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
    [UIView commitAnimations];
}

- (void)initNavBar{
    self.navigationItem.title = @"我的资料";
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 90, 30)];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setFrame:CGRectMake(-30, 0, 90, 30)];
    [leftButton setTitle:@"返回" forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [leftButton setTitleColor:[UIColor colorWithWhite:0.200 alpha:1.000] forState:UIControlStateNormal];
    [leftButton setTitleColor:[UIColor colorWithRed:0.991 green:0.532 blue:0.303 alpha:1.000] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftButton setImage:[UIImage imageNamed:@"back_touch"] forState:UIControlStateHighlighted];
    [view addSubview:leftButton];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.leftBarButtonItem = barButtonItem;
}

-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initViews{
    
    self.imgHead.clipsToBounds = YES;
    self.imgHead.layer.cornerRadius = 5;
    self.vShow.layer.cornerRadius = 5;
    self.vShow.alpha = 0;
    self.txfName.layer.cornerRadius = 5;
    self.btnCancel.clipsToBounds = YES;
    self.btnCancel.layer.cornerRadius = 3;
    self.btnSure.clipsToBounds = YES;
    self.btnSure.layer.cornerRadius = 3;
}

-(void)addGestures{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapHandle:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tap];
}

-(void)tapHandle:(UITapGestureRecognizer *)tap{
    [self.txfName resignFirstResponder];
}

-(void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - btnAction
-(IBAction)queding_Action:(UIButton *)sender {
    [self dimissKeyboard];
    
    NSData *userData = [KStandUserDefaults objectForKey:KUserDefaultKey_PersonalDetail];
    PersonalDetail *user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    NSString *postUrl = [NSString stringWithFormat:@"%@%@",KinterFace_memberUpdate,user.objectId];
    NSDictionary *parameters = @{@"f":@"nickname",
                                 @"v":self.txfName.text};
    [HttpRequestManager putMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]  parameters:parameters completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            user.nickname = self.txfName.text;
            NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:user];
            [KStandUserDefaults setObject:userData forKey:KUserDefaultKey_PersonalDetail];
            [KStandUserDefaults synchronize];
            self.lblName.text = user.nickname;
            [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginCityStarViewSuccess" object:nil];
            [UIView animateWithDuration:0.6f animations:^{
                self.vShow.alpha = 0;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];

}

-(IBAction)cancle_Action:(UIButton *)sender {
    [self dimissKeyboard];
    [UIView animateWithDuration:0.6f animations:^{
        self.vShow.alpha = 0;
    }];
}

-(void)dimissKeyboard
{
    [self.txfName resignFirstResponder];
}

- (IBAction)xiugai_Action:(id)sender {
    [UIView animateWithDuration:0.6f animations:^{
        self.vShow.alpha = 1;
    }];
}

- (IBAction)xiugaiBackground_Action:(id)sender {
    [self.view endEditing:YES];
    self.selectWhichOne = KselectImagePickerBackground;
    __block UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    
    RIButtonItem *choosePhotoButton = [RIButtonItem itemWithLabel:@"从相册选取" action:^{
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    
    UIActionSheet *imageSourcePickActionSheet;
    
    imageSourcePickActionSheet = [[UIActionSheet alloc] initWithTitle:@"添加照片" cancelButtonItem:nil destructiveButtonItem:[RIButtonItem itemWithLabel:@"取消"] otherButtonItems:choosePhotoButton,nil];
    [imageSourcePickActionSheet showInView:self.view];
}

- (IBAction)touxiu_Action:(UITapGestureRecognizer *)sender {
    [self.view endEditing:YES];
    self.selectWhichOne = KselectImagePickerAvatar;
    
    __block UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    
    RIButtonItem *takePhotoButton = [RIButtonItem itemWithLabel:@"拍照" action:^{
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    RIButtonItem *choosePhotoButton = [RIButtonItem itemWithLabel:@"从相册选取" action:^{
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    
    UIActionSheet *imageSourcePickActionSheet;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imageSourcePickActionSheet = [[UIActionSheet alloc] initWithTitle:@"添加照片" cancelButtonItem:nil destructiveButtonItem:[RIButtonItem itemWithLabel:@"取消"] otherButtonItems:takePhotoButton,choosePhotoButton,nil];
    }else{
        imageSourcePickActionSheet = [[UIActionSheet alloc] initWithTitle:@"添加照片" cancelButtonItem:nil destructiveButtonItem:[RIButtonItem itemWithLabel:@"取消"] otherButtonItems:choosePhotoButton,nil];
    }
    [imageSourcePickActionSheet showInView:self.view];
    
}

-(IBAction)recoverDefaltBackImage:(id)sender
{
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"defaultImage"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [SVProgressHUD showSuccessWithStatus:@"恢复背景成功"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeBackGroundImage"object:self];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    if (self.selectWhichOne == KselectImagePickerAvatar) {
        [picker dismissViewControllerAnimated:YES completion:^{
            [UpLoadImageManager uploadImage:editingInfo[UIImagePickerControllerOriginalImage] withCompltedBlock:^(BOOL success, NSString *urlString) {
                if (success) {
                    [HttpRequestManager putMethod:KinterFace_memberAvatar parameters:@{@"id":urlString} completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
                        if (success) {
                            NSData *userData = [KStandUserDefaults objectForKey:KUserDefaultKey_PersonalDetail];
                            PersonalDetail *user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
                            user.avatar = urlString;
                            NSData *userDatas = [NSKeyedArchiver archivedDataWithRootObject:user];
                            [KStandUserDefaults setObject:userDatas forKey:KUserDefaultKey_PersonalDetail];
                            [KStandUserDefaults synchronize];
                            self.imgHead.image = editingInfo[UIImagePickerControllerOriginalImage];
                            [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginCityStarViewSuccess" object:self userInfo:nil];
                        }else{
                            [SVProgressHUD showErrorWithStatus:errMsg];
                        }
                    }];
                }
            }];
        }];
    }else{
        [picker dismissViewControllerAnimated:YES completion:^{
            UIImage *imageone = editingInfo[UIImagePickerControllerOriginalImage];
            UIImage * HeardImage = [self imageWithImageSimple:imageone scaledToSize:CGSizeMake(imageone.size.width/2, imageone.size.height/2)];
            NSLog(@"%f,%f",imageone.size.width,imageone.size.height);
            NSLog(@"%f,%f",HeardImage.size.width,HeardImage.size.height);
            NSData *imageData = UIImageJPEGRepresentation(HeardImage, 100);
            [[NSUserDefaults standardUserDefaults]setObject:imageData forKey:@"defaultImage"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [SVProgressHUD showSuccessWithStatus:@"背景保存成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeBackGroundImage"object:self];
        }];
    }
}

-(UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    return newImage;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
